<?php
session_start();

include_once("auth_process.php");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    processPostRequest();
} else {
    $authResult = validateSession();

    if ($authResult['result'] == true) {
        redirectToDestination($_SESSION['ierg4210']['role']);
    } else {
        $errorCode = $authResult['error'];
        if ($errorCode == $AUTH_NO_SESSION) {
            usualProcess();
        } else {
            validationFail("Invalid session {$errorCode}");
        }
    }
}
function processPostRequest()
{
    if (!isset($_POST['login_token']) || $_POST['login_token'] != $_SESSION['login_token']) {
        validationFail("Invalid login token!");
    }
    refreshLoginToken();

    $email = $_POST['email'];
    $user = getUserByEmail($email);

    if ($user == null) {
        validationFail("Invalid email or password!");
    } else {
        $password = $_POST['password'];
        $salt = $user['salt'];
        $pass_hash = $user['pass_hash'];
        $role = $user['role'];
        $current_hash = hash_hmac("sha256", $password, $salt);
        if ($current_hash != $pass_hash) {
            validationFail("Invalida email or password");
        } else {
            session_regenerate_id();
            createSession($user['email'], $user['role'], $user['uname'], $user['uid']);
            updateSessionAndCookie();
            redirectToDestination($user['role']);
        }
    }
}

function usualProcess()
{
    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
        refreshLoginToken();
        include("login_form.php");
        exit();
    } else {
        processPostRequest();
    }
}

function refreshLoginToken()
{
    $login_token = md5(time() . "login_token" . rand(0, 9999));
    $_SESSION['login_token'] = $login_token;
}

function validationFail($failMsg)
{
    include("login_form.php");
    echo "<script>alert(\"{$failMsg}\")</script>";
    exit();
}

function redirectToDestination($role)
{
    if ($role == 0) {//admin
        header("Location: shop_manage.php");
        exit();
    } else if ($role == 1) {//common user
        header("Location: index.php");
        exit();
    }
}